<!-- 验证码登录 -->
<template>
  <div class="login check-login" ref="login">
    <!-- 输入手机 -->
    <transition name="page">
      <div class="send" v-if="link==1">
        <div class="login-title clearfix">
          <span>{{isReset ? '找回密码' : '验证码登录'}}</span>
          <p v-show="!isReset">
            登录表示同意
            <i>用户协议</i>和
            <i>隐私政策</i>
          </p>
          <p v-show="isReset">请输入绑定的手机号</p>
        </div>
        <div class="login-input">
          <input
            type="number"
            placeholder="请输入手机号码"
            v-model="phone"
            maxlength="13"
            oninput="if(value.length>13)value=value.slice(0,13)"
          />
          <span class="clean" v-show="phone!=''" @click="cleanClick()"></span>
        </div>
        <div :class="['login-btn shadow2',canSend ? 'can-login' :'']" @click="sendCode()">获取验证码</div>
        <!-- <div :class="['round-btn',canSend ? 'can-login shadow2' :'']" @click="sendCode()"></div> -->
        <div class="login-tab clearfix" v-show="!isReset && bottomShow && !isDing">
          <span class="left" @click="loginTab(1)">师生通用户登录</span>
          <i class="left"></i>
          <span class="left" @click="loginTab(2)">快乐学堂用户登录</span>
        </div>
      </div>
    </transition>
    <!-- 验证码 -->
    <transition name="page">
      <div class="check" v-if="link==2">
        <div class="login-title clearfix">
          <span>输入验证码</span>
          <p>
            验证码已发送至
            <i>+86{{phone}}</i>
          </p>
        </div>
        <div class="check-input">
          <ul class="num-list clearfix">
            <li class="num-box left" v-for="(item,index) in boxList" :key="index">
              <div class="cursor" v-if="checkNum.length===index"></div>
              <div class="num" v-if="checkNum.length>=index+1">{{numList[index]}}</div>
            </li>
          </ul>
          <input
            class="check-num"
            type="number"
            v-model="checkNum"
            maxlength="6"
            focus="true"
            auto-focus="true"
            oninput="if(value.length>6)value=value.slice(0,6)"
          />
        </div>
        <!-- <div class="login-input clearfix">
                    <input type="number" placeholder="验证码" v-model="checkNum"  maxlength="6" oninput="if(value.length>6)value=value.slice(0,6)">
                    <span class="clean"  v-show="checkNum!=''" @click="cleanClick()"></span>
        </div>-->
        <div class="btn-send">
          <i v-show="countdown>0">重新获取（{{countdown}}s）</i>
          <span v-show="countdown==0" @click="sendCode()">重新获取</span>
        </div>
        <div
          v-show="waiting!=1"
          :class="['login-btn shadow2',canLogin ? 'can-login' :'']"
          @click="goLogin()"
        >登 录</div>
        <div v-show="waiting==1" class="round-btn can-login shadow2 waiting">
          <span></span>
        </div>
        <!-- <div :class="['round-btn',canLogin ? 'can-login shadow2' :'',{'waiting':waiting==1}]" @click="goLogin()">
                    <span v-show="waiting==1"></span>
        </div>-->
      </div>
    </transition>
    <transition name="fadedown">
      <Warning v-show="warnShow" :warnShow="warnShow" :warnText="warnText"></Warning>
    </transition>
  </div>
</template>

<script>
import Warning from "@/components/Warning";
import { axGet, axPost } from "@/api/index";
import { getUserList, bindDingTalkUserId } from "@/api/index";
import { iosSystem } from "@/assets/js/base";
import * as dd from 'dingtalk-jsapi'; //钉钉微应用

export default {
  name: "index",
  components: {
    Warning
  },
  data() {
    return {
      isReset: this.$route.query.isreset, //找回密码流程
      link: 1, //1输入手机号状态，2输入验证码状态
      phone: localStorage.getItem("readPhone")
        ? localStorage.getItem("readPhone")
        : "", //手机号
      boxList: Array(6),
      numList: [],
      checkNum: "", //验证码
      checkValue: "", //正确验证码
      canSend: false, //是否可发送
      canLogin: false, //是否可登录
      waiting: 0,
      timeLoop: {}, //计时器
      countdown: 60, //倒计时
      bodyHeight: 0,
      bottomShow: true,
      //提示窗
      warnShow: false,
      warnText: "",

      userId: this.$route.query.userid, //直接登录

      corpId: this.$route.query.corpId, //钉钉
      duserid: "", //钉userId

      //公众号
      appIdTest: "wxcaed756334ceb07e",
      webUrl: "http://www.91118.com/activity/HappyReadingV2/",
      codeId: getParames("code") ? getParames("code") : _getParames("code"),
      appId: getParames("state") ? getParames("state") : _getParames("state"),
      unionid: "",
      openid: "",

      roleList: []
    };
  },
  watch: {
    phone(newVal, oldVal) {
      if (newVal) {
        let reguP = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        reguP.test(this.phone) ? (this.canSend = true) : (this.canSend = false);
      }
    },
    checkNum(newVal, oldVal) {
      this.numList = newVal.split("");
      if (newVal.length == 6) {
        this.canLogin = true;
      }
    }
  },
  created() {
    this.$parent.menuShow = false;

    let reguP = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    reguP.test(this.phone) ? (this.canSend = true) : (this.canSend = false);

    this.getUserInfo();
    this.wxLogin();
    let scope =
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      this.appIdTest +
      "&redirect_uri=" +
      escape(this.webUrl) +
      "&response_type=code&scope=snsapi_userinfo&state=" +
      this.appIdTest +
      "#wechat_redirect";
    //  console.log('scope');
    if (getParames("duserid")) {
      // console.log("getParames-----", getParames("duserid"));
      dd.ui.webViewBounce.disable()
      this.duserid = getParames("duserid");
      this.getUserList();
    }

    // if(this.corpId){
    //     dd.ready(() => {
    //         dd.runtime.permission.requestAuthCode({
    //             corpId: this.corpId,    // 企业id
    //             onSuccess: (info) => {
    //                 code = info.code // 通过该免登授权码可以获取用户身份
    //             }
    //         });
    //     });
    // }
  },
  mounted() {
    this.$nextTick(() => {
      this.bodyHeight = this.$refs["login"].clientHeight;
      if (!iosSystem()) {
        window.addEventListener("resize", () => {
          let height = this.$refs["login"].clientHeight;
          if (height < this.bodyHeight) {
            this.bottomShow = false;
          } else {
            this.bottomShow = true;
          }
        });
      }
    });
    // if (window.history && window.history.pushState) {
    //     history.pushState(null, null, document.URL);
    //     window.addEventListener('popstate', this.goBack, false);
    // }
  },
  computed: {
    isDing: function() {
      if (getParames("duserid")) {
        return true;
      } else {
        return false;
      }
    }
  },
  // destroyed(){
  //     window.removeEventListener('popstate', this.goBack, false);
  // },
  methods: {
    // goBack(){
    //     this.$router.replace({path: '/login'});
    // },
    //判断是否可以免登录
    getUserList() {
      const data = {
        DingTalkUserId: this.duserid,
        // corpId:'dingaedad32f11123112'
        corpId: getParames("corpId")
      };
      getUserList(data).then(res => {
        if (res.resultCode == 1 && res.value == []) {
          console.log("-----无免登陆");
        } else if (res.resultCode == 1 && res.value.length > 0) {
          console.log("-----直接登录", res.value);
          //师生通用户列表转换快乐学堂用户用户列表
			this.changeRoleList(res.value)
        } else {
          console.log("-----获取失败");
        }
      });
	},
	//师生通用户列表转换快乐学堂用户列表
	changeRoleList(list){
		axPost("SSTUserToKlxtUser", {
			sstuserids:list.join(",")
		}).then(res => {
		console.log("res", res);
		if (res.ResultCode == 1) {
			if (res.Value && res.Value.length > 0) {
			sessionStorage.setItem("rolesList", JSON.stringify(res.Value));
			if (res.Value.length == 1) {
				this.$parent.myInfo = res.Value[0];
				if (this.$parent.myInfo.ClassList.length > 0) {
				this.getClassName();
				} else {
					sessionStorage.setItem(
					"myInfo",
					JSON.stringify(this.$parent.myInfo)
					);
					this.$router.replace({ path: "/bookshelf", query: {} });
				}
			} else {
				this.$router.push({ path: "/roles", query: {} });
			}
			}
		} else {
			console.log("接口请求失败");
		}
		});
	},

    loginTab(type) {
      this.$router.replace({ path: "/login", query: { type: type } });
    },
    // 直接登录
    getUserInfo() {
      if (this.userId) {
        axGet("GetUserInfo", {
          userId: this.userId
        }).then(res => {
          if (res.ResultCode == 1) {
            sessionStorage.setItem("rolesList", JSON.stringify([res.Value]));
            this.$parent.myInfo = res.Value;
            if (this.$parent.myInfo.ClassList.length > 0) {
              this.getClassName();
            } else {
              sessionStorage.setItem(
                "myInfo",
                JSON.stringify(this.$parent.myInfo)
              );
              this.$router.replace({ path: "/bookshelf", query: {} });
            }
          } else {
            this.warnShow = true;
            this.warnText = "请用手机号登录";
          }
        });
      }
    },
    // 公众号微信绑定登录
    wxLogin() {
      if (this.codeId) {
        axGet("GetKlxtWxUserInfoByCode", {
          appid: this.appId,
          code: this.codeId
        }).then(res => {
          this.unionid = res.Value.unionid;
          this.openid = res.Value.openid;
          window.sessionStorage.setItem("openid", this.openid);
          this.getWXuserInfo();
        });
      }
    },
    getWXuserInfo() {
      axGet("GetuserInfoByUnionId", {
        UnionId: this.unionid,
        platform: "WX", //QQ,WX
        getUserType: "all", //获取用户类型,student,teacher,all,sst,sststudent,sstteacher
        getsst: ""
      }).then(res => {
        if (res.ResultCode == 1) {
          sessionStorage.setItem("rolesList", JSON.stringify(res.Value));
          if (res.Value.length == 1) {
            this.$parent.myInfo = res.Value[0];
            if (this.$parent.myInfo.ClassList.length > 0) {
              this.getClassName();
            } else {
              sessionStorage.setItem(
                "myInfo",
                JSON.stringify(this.$parent.myInfo)
              );
              this.$router.replace({ path: "/bookshelf", query: {} });
            }
          } else {
            this.$router.replace({ path: "/roles", query: {} });
          }
        } else {
          this.warnShow = true;
          this.warnText = "请用手机号登录";
        }
      });
    },
    //绑定微信
    toBindWX(userIdList) {
      axPost("BindUnionId", {
        phone: this.phone,
        UnionId: this.unionid,
        OpenId: this.openid,
        AppId: this.appId,
        platform: "WX",
        userIdList: userIdList
      }).then(res => {
        console.log("绑定成功");
      });
    },
    // 清除
    cleanClick() {
      if (this.link == 1) {
        this.phone = "";
        this.canSend = false;
      } else if (this.link == 2) {
        this.checkNum = "";
        this.canLogin = false;
      }
    },
    //发送验证码
    sendCode() {
      if (this.canSend) {
        axGet("ForgetPassSendSms", {
          phone: this.phone,
          cmd: this.isReset == 1 ? "forgetpass" : "login"
        }).then(res => {
          if (res.ResultCode == 1) {
            this.checkValue = res.Value;
            this.link = 2;
            this.countdown = 60;
            this.timer();
          } else if (res.ResultCode == -3) {
            this.warnShow = true;
            this.warnText = "验证码已达上限，请明日再试";
          } else {
            this.warnShow = true;
            this.warnText = "验证码发送失败";
          }
        });
      }
    },
    // 登录
    goLogin() {
      if (this.canLogin && this.waiting != 1) {
        this.waiting = 1;
        localStorage.setItem("readPhone", this.phone);
        if (this.checkNum == this.checkValue) {
          axPost("ForgetPassCheckRandCode", {
            phone: this.phone,
            code: this.checkNum,
            getuser: "1",
            getUserType: "all",
            // strGetsst:this.isReset==1 ? 'yes':'no',
            getsst: this.isReset == 1 ? "yes" : "no"
          }).then(res => {
            if (res.ResultCode == 1) {
              sessionStorage.setItem("rolesList", JSON.stringify(res.Value));
              this.roleList = res.Value;
              //钉钉
              if (this.duserid) {
                this.bindDingTalkUserId();
              }
              if (this.codeId) {
                //微信公众号内登录
                let userIdList = "";
                res.Value.forEach((item, i) => {
                  if (i == 0) {
                    userIdList = item.UserId;
                  } else {
                    userIdList = userIdList + "," + item.UserId;
                  }
                });
                this.toBindWX(userIdList);
              }
              if (this.isReset == 1) {
                //找回密码
                if (res.Value.length > 0) {
                  this.$router.push({ path: "/roles", query: { isreset: 1 } });
                } else {
                  this.$LayerTip({
                    content: "对不起，请联系您的老师或者管理员修改您的登录密码",
                    time: 3000
                  });
                }
              } else {
                //登录
                if (res.Value.length == 1) {
                  this.$parent.myInfo = res.Value[0];
                  if (this.$parent.myInfo.ClassList.length > 0) {
                    this.getClassName();
                  } else {
                    sessionStorage.setItem(
                      "myInfo",
                      JSON.stringify(this.$parent.myInfo)
                    );
                    this.$router.replace({ path: "/bookshelf", query: {} });
                  }
                } else {
                  this.$router.push({ path: "/roles", query: {} });
                }
              }
            } else if (res.ResultCode == -5) {
              this.warnShow = true;
              this.warnText = "账号或密码错误";
              this.waiting = 2;
            } else {
              this.warnShow = true;
              this.warnText = "登录失败";
              this.waiting = 2;
            }
          });
        } else {
          this.warnShow = true;
          this.warnText = "验证码错误";
          this.waiting = 2;
        }
      }
    },
    //获取班级
    getClassName() {
      let classStr = "";
      let classJson = [];
      this.$parent.myInfo.ClassList.forEach((code, i) => {
        classStr = classStr + "," + code;
        let list = {
          chose: false,
          code: code,
          name: ""
        };
        classJson.push(list);
      });
      axGet("GetClassName", {
        ClassIds: classStr
      }).then(res => {
        if (res.ResultCode == 1) {
          classJson.forEach((item, i) => {
            item.name = res.Value[item.code];
          });
          this.$parent.myInfo.classJson = classJson;

          sessionStorage.setItem("myInfo", JSON.stringify(this.$parent.myInfo));
          this.$router.replace({ path: "/bookshelf", query: {} });
        }
      });
    },
    /* 计时器 */
    timer() {
      this.timeLoop = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timeLoop);
        }
      }, 1000);
    },
    // 绑定钉钉和师生通用户关系
    bindDingTalkUserId() {
      let userIdList = [];
      this.roleList.length > 0 &&
        this.roleList.forEach(element => {
          if (element.Sourcecode && element.Sourcecode !== "") {
            userIdList.push(element.Sourcecode);
          }
        });
      let SSTUserIds = userIdList.join(",");
      const data = {
        DingTalkUserId: this.duserid,
        SSTUserIds: SSTUserIds,
        // corpId:'dingaedad32f11123112'
        corpId: getParames("corpId")
      };
      bindDingTalkUserId(data).then(res => {
        console.log("绑定成功");
      });
    }
  }
};
</script>